﻿using System.Collections.Generic;
using UnityEngine;

namespace UFrame
{
    public static class TransformTool
    {
        public static void RemoveAllChildren(this Transform parent)
        {
            if (parent == null || parent.childCount == 0)
            {
                return;
            }

            List<Transform> children = new List<Transform>();
            for (int i = 0; i < parent.childCount; ++i)
            {
                children.Add(parent.GetChild(i));
            }

            foreach (var child in children)
            {
                GameObject.Destroy(child.gameObject);
            }

            children.Clear();
        }

        public static void AddChild(this Transform parent, Transform child)
        {
            if (child == null)
            {
                return;
            }

            child.SetParent(parent);
            child.transform.localPosition = Vector3.zero;
            child.transform.localScale = Vector3.one;
            child.transform.localRotation = Quaternion.identity;
        }

        public static Transform RecursionSearch(this Transform t, string name)
        {
            if (t.name == name)
            {
                return t;
            }

            if (t.childCount == 0)
            {
                return null;
            }

            Transform result = null;
            for (int i = 0; i < t.childCount; i++)
            {
                var temp = t.GetChild(i);
                result = RecursionSearch(temp, name);
                if (result != null)
                {
                    break;
                }
            }

            return result;
        }

        public static Transform FindEnd(this Transform go, string name)
        {
            var oList = go.GetComponentsInChildren(typeof(Transform), true);

            foreach (var node in oList)
            {
                if (node.name == name)
                {
                    return node.transform;
                }
            }

            return null;
        }
        
        /// <summary>
        /// 转换Transforms 成为路径
        /// </summary>
        public static Vector3 [] ToPaths(this List<Transform> go)
        {
            Vector3 [] v3s = new Vector3[go.Count];
            for (int i = 0; i < go.Count; i++)
            {
                v3s[i] = go[i].position;
            }
            return v3s;
        }
        
    }
}